package uploadfile

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
)

// 合并分块文件
func MergeChunks(tempDir string, destDir string, fileName string, totalChunks int) (string, uint, error) {
	var fileSize uint
	var destinationFilePath string
	// 创建目标目录
	err := os.MkdirAll(tempDir, os.ModePerm)
	if err != nil {
		err := fmt.Errorf("创建临时目录失败: %s", err.Error())
		return destinationFilePath, fileSize, err
	}

	err = os.MkdirAll(destDir, os.ModePerm)
	if err != nil {
		err := fmt.Errorf("创建目标目录失败: %s", err.Error())
		return destinationFilePath, fileSize, err
	}

	// 创建目标文件
	destinationFilePath = filepath.Join(destDir, fileName)
	destinationFile, err := os.Create(destinationFilePath)
	if err != nil {
		err := fmt.Errorf("创建目标文件失败: %s", err.Error())
		return destinationFilePath, fileSize, err

	}
	defer destinationFile.Close()

	// 合并分片
	for i := 0; i < totalChunks; i++ {
		tempFilePath := filepath.Join(tempDir, fmt.Sprintf(fileName+"_%d", i))
		// tempFile, err := os.Open(tempFilePath)

		_, err := os.Stat(tempFilePath)
		if os.IsNotExist(err) {
			err := fmt.Errorf("文件不存在: %s", err.Error())
			return destinationFilePath, fileSize, err

		}

		tempFile, err := os.OpenFile(tempFilePath, os.O_RDONLY, 0666)
		if err != nil {
			err := fmt.Errorf("文件打开失败: %s", err.Error())
			return destinationFilePath, fileSize, err

		}

		defer tempFile.Close()

		_, err = io.Copy(destinationFile, tempFile)
		if err != nil {
			err := fmt.Errorf("文件复制失败: %s", err.Error())
			return destinationFilePath, fileSize, err
		}
	}

	fileInfo, err := os.Stat(destinationFilePath)
	if err != nil {
		err := fmt.Errorf("查看文件信息失败: %s", err.Error())
		return destinationFilePath, fileSize, err
	}
	fileSize = uint(fileInfo.Size())
	return destinationFilePath, fileSize, nil
}

func DeleteChunks(tempDir string, fileName string, totalChunks int) error {
	for i := 0; i < totalChunks; i++ {
		tempFilePath := filepath.Join(tempDir, fmt.Sprintf(fileName+"_%d", i))
		err := os.Remove(tempFilePath)
		if err != nil {
			return err
		}
	}
	return nil
}
